{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Computer Programming for Social Scientists"},{"metadata":{},"cell_type":"markdown","source":"## Exercise 1: Subsetting (20 points)"},{"metadata":{},"cell_type":"markdown","source":"Write 3 separate subsetting operations to extract the following elements from the list below:\n\n•\tAll consonants from the first character vector\n•\tSecond columns in all dimensions from the array A\n•\tOdd rows from the matrix M\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"l <- list(\n    mapply(assign, letters, 1:26),\n    A = array(1:60, c(5,2,3)),\n    M = matrix(1:50, c(10,5))\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"l\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Exercise 1\n\n#my code\n# All consonants from the first character vector\nletters[letters != c('a','e','i','o','u')]\n\n# Second columns in all dimensions from the array A \n A = array(1:60, c(5,2,3))\nA[,2,]\n\n#odd rows from matrix\n M = matrix(1:50, c(10,5))\nrow_odd <- seq_len(nrow(M)) %% 2\ndata_row_odd <- M[row_odd == 1, ]\ndata_row_odd ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exercise 2: Vectorized operations (20 points)\nUsing function `mean()` calculate the proportion of book titles in the vector below that have more than 10 characters in them (including whitespaces).\nTip: You can use `nchar()` function to calculate the number of characters in a vector\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"books <- c(\n  \"Dubliners\",\n  \"Ulysses\",\n  \"War and Peace\",\n  \"Normal People\",\n  \"Crime and Punishment\",\n  \"The Picture of Dorian Gray\"\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nchar(books)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#only 4 books have more than 10 characters\nmean(13, 13, 20, 26)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exercise 3: Conditional statements and loops (20 points)\nLevenshtein distance is a string distance metric that measures how many transformations (insertion, deletion, substitution) are required to convert one string into another. For example, consider words 'cat' and 'can'. Letter 't' in the first word can be substituted with a character 'n' in order for the two words to become identical.\nFor classical Levenshtein distance each of the transformations has the same cost of 1. In other words, the distance (of 1) is the same between the word pairs 'cat' - 'can' and 'cat' - 'cats'.\nBelow you can see two character vectors that were transformed to have a single letter as an individual element. Write a loop to compare each of the elements from one string to each of the elements from another string while keeping track of the number of transformations. Print out the result of the transformations count.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"char_1 <- unlist(strsplit(\"kitten\", split = \"\"))\nchar_2 <- unlist(strsplit(\"sitting\", split = \"\"))","execution_count":9,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"char_1","execution_count":10,"outputs":[{"output_type":"display_data","data":{"text/html":"<style>\n.list-inline {list-style: none; margin:0; padding: 0}\n.list-inline>li {display: inline-block}\n.list-inline>li:not(:last-child)::after {content: \"\\00b7\"; padding: 0 .5ex}\n</style>\n<ol class=list-inline><li>'k'</li><li>'i'</li><li>'t'</li><li>'t'</li><li>'e'</li><li>'n'</li></ol>\n","text/markdown":"1. 'k'\n2. 'i'\n3. 't'\n4. 't'\n5. 'e'\n6. 'n'\n\n\n","text/latex":"\\begin{enumerate*}\n\\item 'k'\n\\item 'i'\n\\item 't'\n\\item 't'\n\\item 'e'\n\\item 'n'\n\\end{enumerate*}\n","text/plain":"[1] \"k\" \"i\" \"t\" \"t\" \"e\" \"n\""},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"char_2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#my code in python\ndef dist(X, m, Y, n):\n \n    # base case: empty strings (case 1)\n    if m == 0:\n        return n\n \n    if n == 0:\n        return m\n \n    # if the last characters of the strings match (case 2)\n    cost = 0 if (X[m - 1] == Y[n - 1]) else 1\n \n    return min(dist(X, m - 1, Y, n) + 1,        # deletion (case 3a))\n            dist(X, m, Y, n - 1) + 1,           # insertion (case 3b))\n            dist(X, m - 1, Y, n - 1) + cost)    # substitution (case 2 + 3c)\n \n \nif __name__ == '__main__':\n \n    X = 'cat'\n    Y = 'can'\n \n    print('The Levenshtein distance is', dist(X, len(X), Y, len(Y)))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exercise 4: Defining and calling functions (20 points)\n\nLet's revisit Euclidean distance from the previous assignment. As you remember Euclidean distance between two points gives the length of a line segment between them (as the crow flies distance).\nWrite a function that takes two vectors of arbitrary lengths as coordinates and calculates Euclidean distance between them.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# my code\n\n## Assigning each vector a variable name\n### First pair\na <- c(3, 1, 5, 7, 1)\nb <- c(4, 5, 2, 7, 1)\n### Second pair\nc <- c(12, 0, 15, 1, 2)\nd <- c(0, 10, 1, 9, 6)\n# The function\n\n\neuclidean <- function(a, b){\n  sqrt(sum((a - b)^2))\n  \n} \n# Call the function eucl supplying pair 1 as an arguments.\neuclidean(a,b)\n# Call the function eucl supplying pair 2 as an arguments.\neuclidean(c,d)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exercise 5: Fibonacci sequence (20 points)\nWe already encountered Fibonacci sequence in this module before. Recall that:\n•\tFibonacci sequence starts with the first element equal to 0 and the second element equal to 1\n•\tAll subsequent elements are the sums of the preceeding two elements\n•\tThe beginning of the sequence then looks like this: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]\nImplement a function that takes a vector of integers as an input and returns a vector of numbers from Fibonacci sequence, whose indices correspond to the integers from the input vector.\nTest the implemented function on the following inputs:\n•\t10\n•\tc(1, 2, 3, 4, 5)\n•\tc(3, 9, 12)\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":" Fibonacci <- function(n){\n  Fibonacci <- numeric(n)\n  Fibonacci[1] <- Fibonacci[2] <- 1\n  for (i in 3:n) Fibonacci[i] <- Fibonacci[i - 2] + Fibonacci[i - 1]\n  print(Fibonacci)\n  \n}\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test\nFibonacci(10)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"ir","display_name":"R","language":"R"},"language_info":{"name":"R","codemirror_mode":"r","pygments_lexer":"r","mimetype":"text/x-r-source","file_extension":".r","version":"3.6.3"}},"nbformat":4,"nbformat_minor":5}